/**
 * Created by John on 2016/7/12.
 */
var mongo = new Mongo('localhost');
var wordsDB = mongo.getDB('BeginningMongoDB');
var wordsColl = wordsDB.getCollection('word_stats');

var cursor = wordsColl.aggregate(
    {
        $match: {
            first: {
                $in: ['a', 'e', 'i', 'o', 'u']
            }
        }
    },
    {
        $group: {
            _id: '$first',
            largest: {$max: '$size'},
            smalllest: {$min: '$size'},
            total: {$sum: 1}
        }
    },
    {$sort: {_id: 1}}
);
print('Largest and smallest word sizes for words beginning with a vowel:');
cursor.forEach(function (item) {
    print(JSON.stringify(item));
});

cursor = wordsColl.aggregate(
    {$match: {size: 4}},
    {$limit: 5},
    {$project: {_id: "$word", stats: 1}}
);
print('Stats for 5 four letter words:');
cursor.forEach(function (item) {
    print(JSON.stringify(item));
});

cursor = wordsColl.aggregate(
    {$group:{_id:'$first',average:{$avg:'$size'}}},
    {$sort: {average: -1}},
    {$limit:5}
);
print('First letter of top 6 largest average word size:');
cursor.forEach(function (item) {
    print(JSON.stringify(item));
});